#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2017/11/2 13:14
# @Author  : Yunhao.Cao
# @File    : main.py
from __future__ import absolute_import, unicode_literals
from bs4 import BeautifulSoup
import requests

__author__ = 'Yunhao.Cao'

__ALL__ = []


def main():
    """
    解析页面：https://detail.tmall.com/item.htm?spm=a220o.1000855.1000983.1.5e5181f0KzLx4W&id=540405579912&standard=1&sku_properties=5919063:6536025
    提取品牌名称，售价，月销量，累计评价数

    * CSS选择器
    :return:
    """
    # 编码问题
    import sys
    reload(sys)
    sys.setdefaultencoding('utf8')

    root_url = "https://detail.tmall.com"
    detail_url = root_url + "/item.htm?id=540405579912"

    # 获取soup
    response = requests.get(detail_url)
    soup = BeautifulSoup(response.text, "html.parser")
    print(soup.prettify("utf-8"))

    try:
        print("开始解析...")

        # 品牌名
        brand_element = soup.select_one("#J_BrandAttr > div > a")
        if brand_element is not None:
            print("brand name = {}".format(brand_element.text))
        else:
            print("brand name 解析失败。")

        # 价格
        price_element = soup.select_one("#J_StrPriceModBox > span.tm-price")
        if price_element is not None:
            print "price = {}".format(price_element.text)
        else:
            print("price 解析失败。")

        # 月销售量
        sold_element = soup.select_one("li[data-label=\'月销量\'] > span.tm-count")
        if sold_element is not None:
            print "sold num = {}".format(sold_element.text)
        else:
            print("sold 解析失败。")

        # 累计评价数
        comment_num = soup.select_one("#J_ItemRates > span.tm-label")
        if comment_num is not None:
            print "comment num = {}".format(comment_num.text)
        else:
            print("comment num 解析失败。")

    except Exception as e:
        print "解析错误：{}".format(e)


if __name__ == '__main__':
    main()
